/**
 * 修改培训计划
 */
<template>
<vp-dialog ref="editDialogRef">
    <template #title>
        <vp-label zh="新增培训计划" en="Add Training Plan" v-if="type === 'add'"/>
        <vp-label zh="修改培训计划" en="Edit Training Plan" v-else/>
    </template>
    <TrainingPlan ref="trainingPlanRef" :loading="loading" :type="type"></TrainingPlan>
    <template #footer>
        <vp-btn-save v-if="!formData.zt || formData.zt === 10" :loading="saveLoading" @click="handleSave(10)"/>
        <vp-btn-submit :loading="saveLoading" @click="handleSave(20)"/>
    </template>
</vp-dialog>
</template>
<script setup lang="ts" name="editTrainingPlan">
import { ref, reactive, nextTick } from 'vue';
import request from '/@/utils/request';
import TrainingPlan from './TrainingPlan.vue';

const emits = defineEmits(['formSubmited']);
const loading = ref(false);
const saveLoading = ref(false);
const type = ref('add');
const id = ref('');
const formData = reactive({
    id: '',
    zt: 10,
});

const editDialogRef = ref();
const trainingPlanRef = ref();

// 打开弹窗
const handleOpen = (param: {id: string, type: string})=>{
    type.value = param.type;
    id.value = param.id;
    formData.zt = 10;
    editDialogRef.value.handleOpen();
    nextTick(() => {
        if(param.type === 'edit'){
            loading.value = true;
            request.get(`/training/plan/${param.id}`).then((res)=>{
                trainingPlanRef.value.setData({
                    ...res.data,
                });
                formData.zt = res.data.zt;
                loading.value = false;
            })
        } else {
            trainingPlanRef.value.setData({
                ...formData,
            });
        }
    });
}

// 保存
const handleSave = (zt : number) => {
    saveLoading.value = true;
    trainingPlanRef.value.getData(zt).then((data: any) =>{
        request.post("/training/plan/"+type.value, {
            ...data,
            zt: zt,
        }).then((assessment: any)=>{
            emits("formSubmited", assessment.data);
            editDialogRef.value.handleClose();
        }).catch(()=>{
        }).finally(()=>{
            saveLoading.value = false;
        })
    }).catch(()=>{saveLoading.value = false;});
}

defineExpose({
    handleOpen,
})

</script>
